package com.photoeditor.demo.model.store.module;

import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DebugUtil;
import com.common.base.utils.ProcessUtils;
import com.common.base.utils.SystemUtils;
import com.photoeditor.demo.app.TestUser;
import com.photoeditor.demo.db.DataManager;
import com.photoeditor.demo.db.DBHelper;
import com.photoeditor.demo.db.FilterBean;
import com.photoeditor.demo.db.FilterCategoryBean;
import com.photoeditor.demo.db.FilterConstant;
import com.photoeditor.demo.db.FilterStoryBean;
import com.photoeditor.demo.db.FilterStoryBeanDao;
import com.photoeditor.demo.model.preference.ChildProcessBroadcastReceiver;
import com.photoeditor.demo.util.FileUtil;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

//import com.photoeditor.demo.db.BackgroundBean;
//import com.photoeditor.demo.db.BackgroundCategoryBean;

/**
 * Created by mutour on 2017/5/9.
 */

public class StoreOnlineManager extends BaseOnlineManager implements ChildProcessBroadcastReceiver.OnMainProcessMsgListener {
    private static final String STORE_ROOT_URL = "superpro-soft/photoeditordemo/store-v1";
    private static final String STORE_TEST_ROOT_URL = "superpro-soft/photoeditordemo/store-test-v1";
    private static final String FILE_NAME_STORE = "store";

    /**
     * 商店滤镜模块id
     */
    public static final String MODULE_ID_FILTER = "101";
    /**
     * 商店贴纸模块id
     */
    public static final String MODULE_ID_STICKER = "201";

    /**
     * 背景模块id
     */
    public static final String MODULE_ID_BACKGROUND = "301";

    /**
     * 模板模块id
     */
    public static final String MODULE_ID_TEMPLATE = "401";
    private StoreOnlineManager() {
        super();
        ChildProcessBroadcastReceiver.getInstance().registerListener(this);
    }
    private static class SingletonHolder {
        private static final StoreOnlineManager INSTANCE = new StoreOnlineManager();
    }

    @Override
    protected Config getConfig() {
        return new ConfigBuilder(STORE_ROOT_URL, FILE_NAME_STORE)
                .baseTestRequestUrl(STORE_TEST_ROOT_URL)
                .build();
    }

    public static StoreOnlineManager getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private int getItemBeans(StoreOnlineBean storeOnlineBean, boolean bRecursive, ArrayList<StoreOnlineBean> outArr) {
        int count = 0;
        if (storeOnlineBean != null) {
            if (storeOnlineBean.getType() == StoreOnlineBean.TYPE_ITEM) {
                outArr.add(storeOnlineBean);
                count++;
            }
            ArrayList<StoreOnlineBean> childModules = storeOnlineBean.getChildModules();
            if (childModules != null && bRecursive) {
                for (StoreOnlineBean bean : childModules) {
                    count += getItemBeans(bean, bRecursive, outArr);
                }
            }
        }
        return count;
    }

    private int getTemplateItemBeans(StoreOnlineBean storeOnlineBean, int supportImgNum, ArrayList<StoreOnlineBean> outArr) {
        int count = 0;
        if (storeOnlineBean != null) {
            if (storeOnlineBean.getType() == StoreOnlineBean.TYPE_ITEM && Integer.valueOf(storeOnlineBean.getParam()) >= supportImgNum) {
                outArr.add(storeOnlineBean);
                count++;
            }
            ArrayList<StoreOnlineBean> childModules = storeOnlineBean.getChildModules();
            if (childModules != null) {
                for (StoreOnlineBean bean : childModules) {
                    count += getTemplateItemBeans(bean, supportImgNum, outArr);
                }
            }
        }
        return count;
    }

    private int getCategoryBeans(StoreOnlineBean storeOnlineBean, boolean bRecursive, ArrayList<StoreOnlineBean> outArr) {
        int count = 0;
        if (storeOnlineBean != null) {
            if (storeOnlineBean.getType() == StoreOnlineBean.TYPE_CATEGORY) {
                outArr.add(storeOnlineBean);
                count++;
            }
            ArrayList<StoreOnlineBean> childModules = storeOnlineBean.getChildModules();
            if (childModules != null && bRecursive) {
                for (StoreOnlineBean bean : childModules) {
                    outArr.add(bean);
                    count++;
                }
            }
        }
        return count;
    }

    public ArrayList<StoreOnlineBean> getAllFilterItemBeans() {
        ArrayList<StoreOnlineBean> beans = new ArrayList<>();
        StoreOnlineBean filterBean = getBeanByModuleId(MODULE_ID_FILTER);
        if (filterBean == null) {
            return beans;
        }
        getItemBeans(filterBean, true, beans);
        if (DebugUtil.isDebuggable()) {
            DLog.i(TAG, "filter item count: " + beans.size());
        }
        return beans;
    }

    public ArrayList<StoreOnlineBean> getAllStickerCategoryItemBeans() {
        ArrayList<StoreOnlineBean> beans = new ArrayList<>();
        StoreOnlineBean stickerCategory = getBeanByModuleId(MODULE_ID_STICKER);
        if (stickerCategory == null) {
            return beans;
        }
        getItemBeans(stickerCategory, true, beans);
        if (DebugUtil.isDebuggable()) {
            DLog.i(TAG, "sticker item count: " + beans.size());
        }
        return beans;
    }

    public ArrayList<StoreOnlineBean> getAllTemplateItemBeans(int supportImgNum) {
        ArrayList<StoreOnlineBean> beans = new ArrayList<>();
        StoreOnlineBean filterBean = getBeanByModuleId(MODULE_ID_TEMPLATE);
        if (filterBean == null) {
            return beans;
        }
        getTemplateItemBeans(filterBean, supportImgNum, beans);
        if (DebugUtil.isDebuggable()) {
            DLog.i(TAG, "template item count: " + beans.size());
        }
        return beans;
    }

    public ArrayList<StoreOnlineBean> getAllBackgroundCategoryItemBeans() {
        ArrayList<StoreOnlineBean> beans = new ArrayList<>();
        StoreOnlineBean category = getBeanByModuleId(MODULE_ID_BACKGROUND);
        if (category == null) {
            return beans;
        }
        getCategoryBeans(category, true, beans);
        if (DebugUtil.isDebuggable()) {
            DLog.i(TAG, "background category item count: " + beans.size());
        }
        return beans;
    }

    public ArrayList<StoreOnlineBean> getAllBackgroundItemBeans() {
        ArrayList<StoreOnlineBean> beans = new ArrayList<>();
        StoreOnlineBean category = getBeanByModuleId(MODULE_ID_BACKGROUND);
        if (category == null) {
            return beans;
        }
        getItemBeans(category, true, beans);
        if (DebugUtil.isDebuggable()) {
            DLog.i(TAG, "background item count: " + beans.size());
        }
        return beans;
    }

    private StoreOnlineBean getItemBeanById(StoreOnlineBean storeOnlineBean, String id, boolean bRecursive) {
        if (storeOnlineBean == null) {
            return null;
        }
        if (TextUtils.equals(storeOnlineBean.getId(), id)) {
            return storeOnlineBean;
        }
        ArrayList<StoreOnlineBean> childModules = storeOnlineBean.getChildModules();
        if (childModules != null) {
            for (StoreOnlineBean bean : childModules) {
                if (TextUtils.equals(bean.getId(), id)) {
                    return bean;
                }
                if (!bRecursive) {
                    continue;
                }
                return getItemBeanById(bean, id, bRecursive);
            }
        }
        return null;
    }

    private StoreOnlineBean getItemBeanByPackageName(StoreOnlineBean storeOnlineBean, String packageName, boolean bRecursive) {
        if (storeOnlineBean == null) {
            return null;
        }
        if (TextUtils.equals(storeOnlineBean.getPkgName(), packageName)) {
            return storeOnlineBean;
        }
        ArrayList<StoreOnlineBean> childModules = storeOnlineBean.getChildModules();
        StoreOnlineBean onlineBean;
        if (childModules != null) {
            for (StoreOnlineBean bean : childModules) {
                onlineBean = getItemBeanByPackageName(bean, packageName, bRecursive);
                if (onlineBean != null) {
                    return onlineBean;
                }
            }
        }
        return null;
    }

    public StoreOnlineBean getFilterItemBeanById(String id) {
        return getItemBeanById(getBeanByModuleId(MODULE_ID_FILTER), id, true);
    }

    public StoreOnlineBean getFilterItemBeanByPackageName(String packageName) {
        return getItemBeanByPackageName(getBeanByModuleId(MODULE_ID_FILTER), packageName, true);
    }

    public StoreOnlineBean getStickerItemBeanByPackageName(String packageName) {
        return getItemBeanByPackageName(getBeanByModuleId(MODULE_ID_STICKER), packageName, true);
    }

    public StoreOnlineBean getFilterCategoryBeanById(String id) {
        return getItemBeanById(getBeanByModuleId(MODULE_ID_FILTER), id, false);
    }

    public StoreOnlineBean getFilterCategoryBeanByItem(StoreOnlineBean item) {
        String categoryId = item.getCategoryId();
        return getFilterCategoryBeanById(categoryId);
    }

    public StoreOnlineBean getBackgroundCategoryBeanByItem(StoreOnlineBean item) {
        String categoryId = item.getCategoryId();
        return getBackgroundCategoryBeanById(categoryId);
    }

    public StoreOnlineBean getBackgroundCategoryBeanById(String id) {
        return getItemBeanById(getBeanByModuleId(MODULE_ID_BACKGROUND), id, false);
    }

    public ArrayList<StoreOnlineBean> getRecommendBeans(StoreOnlineBean storeOnlineBean) {
        return storeOnlineBean != null ? storeOnlineBean.getRecommends() : null;
    }

    public void requestFilterStory(StoreOnlineBean bean, StoreOnlineListener listener) {
        if (bean.getType() == StoreOnlineBean.TYPE_CATEGORY) {
            ArrayList<StoreOnlineBean> childModules = bean.getChildModules();
            if (childModules != null && childModules.size() > 0) {
                for (StoreOnlineBean childBean : childModules) {
                    requestFilterStory(childBean, null);
                }
            }
        } else if (bean.getType() == StoreOnlineBean.TYPE_ITEM) {
            String story = bean.getStory();
            if (TextUtils.isEmpty(story) || story.startsWith(StoreOnlineBean.STORE_STORY_PREFIX)) {
                return;
            }
            FilterStoryBeanDao dao = DBHelper.getInstance().getDaoSession().getFilterStoryBeanDao();
            Query query = dao.queryBuilder().where(
                    FilterStoryBeanDao.Properties.FilterId.eq(bean.getId()),
                    FilterStoryBeanDao.Properties.CategoryId.eq(bean.getCategoryId())
            ).build();
            List<FilterStoryBean> list = (List<FilterStoryBean>) query.list();
            if (list != null) {
                return;
            }

            String url = story.substring(StoreOnlineBean.STORE_STORY_PREFIX.length());
            StoreNetUtil.getInstance().requestNetworkData(url, new StoreNetUtil.IRequestListener() {
                @Override
                public void onRequestFinish(String text) {
                    if (TextUtils.isEmpty(text)) {
                        return;
                    }
                    try {
                        JSONObject storyJsonObj = new JSONObject(text);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onRequestFailure() {

                }
            });
        }
    }

    public @Nullable String getFilterStore(StoreOnlineBean bean) {
        String country = SystemUtils.getCountry(ComponentContext.getContext());
        return getFilterStore(bean, country);
    }

    public @Nullable String getFilterStore(StoreOnlineBean bean, String country) {

        String story = bean.getStory();
        if (TextUtils.isEmpty(story)) {
            return null;
        }

        if (!story.startsWith(StoreOnlineBean.STORE_STORY_PREFIX)) {
            return story;
        }

        String id = bean.getId();
        String categoryId = bean.getCategoryId();

        FilterStoryBeanDao dao = DBHelper.getInstance().getDaoSession().getFilterStoryBeanDao();
        Query query = dao.queryBuilder().where(
                FilterStoryBeanDao.Properties.FilterId.eq(id),
                FilterStoryBeanDao.Properties.CategoryId.eq(categoryId),
                FilterStoryBeanDao.Properties.Country.eq(country)
        ).build();
        List<FilterStoryBean> list = (List<FilterStoryBean>) query.list();
        if (list == null || list.size() == 0) {
            query = dao.queryBuilder().where(
                    FilterStoryBeanDao.Properties.FilterId.eq(id),
                    FilterStoryBeanDao.Properties.CategoryId.eq(categoryId),
                    FilterStoryBeanDao.Properties.Country.eq(StoreOnlineBean.STORE_STORY_OTHER_COUNTRY)
            ).build();
            list = (List<FilterStoryBean>) query.list();
        }
        if (list != null && list.size() > 0) {
            return list.get(0).getStory();
        }
        return null;
    }


    public boolean isInstalledCategoryById(String categoryId) {
        boolean ret = false;
        if (!TextUtils.isEmpty(categoryId)) {
            ret = DataManager.getInstance().isExistFilterCategory(categoryId);
        }
        return ret;
    }

    public static FilterBean toFilterBean(StoreOnlineBean bean, String filePath) {
        FilterBean filterBean = null;
        if (bean != null) {
            filterBean = new FilterBean();
            filterBean.setName(bean.getName());
            if (bean.getType() == 5) {
                filterBean.setType(FilterConstant.TYPE_ARTISTIC);
            } else {
                filterBean.setType(FilterConstant.TYPE_DOWNLOAD);
            }
            filterBean.setUnLock(FilterConstant.UNLOCK);
//            filterBean.setColor();
            filterBean.setStatus(FilterConstant.STATUS_USE);
//            filterBean.setLocalIndex();
//            filterBean.setImageUrl();
            filterBean.setPackageName(bean.getPkgName());
            filterBean.setDownloadUrl(bean.getDownUrl());
            filterBean.setSize(bean.getSize());
            filterBean.setApkUri(filePath);
            filterBean.setModuleId(bean.getId());
            filterBean.setStory(bean.getStory());
            filterBean.setIcon(bean.getIcon());
            filterBean.setPreview(bean.getPreview());
            filterBean.setLastupdate(bean.getLastUpdate());
            filterBean.setVersionCode(bean.getVersioncode());
            filterBean.setAuthor(bean.getAuthor());
            filterBean.setAuthorUrl(bean.getAuthorUrl());
            filterBean.setCategoryId(bean.getCategoryId());
            filterBean.setBuy(bean.isBuy());
        }
        return filterBean;
    }

    /**
     * 未下载
     */
    public static FilterBean toUndownloadedFilterBean(StoreOnlineBean bean) {
        FilterBean filterBean = null;
        if (bean != null) {
            filterBean = new FilterBean();
            filterBean.setName(bean.getName());
            if (bean.getType() == 5) {
                filterBean.setType(FilterConstant.TYPE_ARTISTIC);
            } else {
                filterBean.setType(FilterConstant.TYPE_DOWNLOAD);
            }
            filterBean.setUnLock(FilterConstant.UNLOCK);
            filterBean.setStatus(FilterConstant.STATUS_USE);
            filterBean.setPackageName(bean.getPkgName());
            filterBean.setDownloadUrl(bean.getDownUrl());
            filterBean.setSize(bean.getSize());
            filterBean.setModuleId(bean.getId());
            filterBean.setStory(bean.getStory());
            filterBean.setIcon(bean.getIcon());
            filterBean.setPreview(bean.getPreview());
            filterBean.setLastupdate(bean.getLastUpdate());
            filterBean.setVersionCode(bean.getVersioncode());
            filterBean.setAuthor(bean.getAuthor());
            filterBean.setAuthorUrl(bean.getAuthorUrl());
            filterBean.setCategoryId(bean.getCategoryId());
            filterBean.setBuy(bean.isBuy());
        }
        return filterBean;
    }

    public static FilterCategoryBean toFilterCategoryBean(StoreOnlineBean bean) {
        FilterCategoryBean categoryBean = null;
        if (bean != null) {
            categoryBean = new FilterCategoryBean();
            categoryBean.setName(bean.getName());
            categoryBean.setType(FilterConstant.TYPE_DOWNLOAD);
            categoryBean.setCategoryId(bean.getId());
            categoryBean.setStory(bean.getStory());
            categoryBean.setLocalIndex(0);
            categoryBean.setIconUrl(bean.getIcon());
            categoryBean.setLastUpdate(bean.getLastUpdate());
            categoryBean.setStyle(bean.getStyle());
            categoryBean.setAuthor(bean.getAuthor());
            categoryBean.setAuthorUrl(bean.getAuthorUrl());
            categoryBean.setBanner(bean.getBanner());
            categoryBean.setUsable(true);
            categoryBean.setPkgName(bean.getPkgName());
            categoryBean.setDownloadOnGP(bean.isDownloadOnGP());
        }
        return categoryBean;
    }

    public static StoreOnlineBean FilaterCatetoryToStoreOnlineBean(FilterCategoryBean bean) {
        StoreOnlineBean rootBean = StoreOnlineManager.getInstance().getFilterCategoryBeanById(MODULE_ID_FILTER);
        ArrayList<StoreOnlineBean> categoryBeans = rootBean.getChildModules();
        if (categoryBeans == null || categoryBeans.isEmpty()) {
            return null;
        }
        for (StoreOnlineBean data: categoryBeans) {
            if (TextUtils.equals(data.getId(), bean.getCategoryId())) {
                return data;
            }
        }
        return null;
    }

    //转换为需解锁滤镜分类bean
    public static FilterCategoryBean toFilterBuyCategoryBean(StoreOnlineBean bean) {
        FilterCategoryBean categoryBean = null;
        if (bean != null) {
            categoryBean = new FilterCategoryBean();
            categoryBean.setName(bean.getName());
            categoryBean.setType(FilterConstant.TYPE_BUY);
            categoryBean.setCategoryId(bean.getId());
            categoryBean.setStory(bean.getStory());
            categoryBean.setIconUrl(bean.getIcon());
            categoryBean.setLastUpdate(bean.getLastUpdate());
            categoryBean.setStyle(bean.getStyle());
            categoryBean.setAuthor(bean.getAuthor());
            categoryBean.setAuthorUrl(bean.getAuthorUrl());
            categoryBean.setBanner(bean.getBanner());
            categoryBean.setUsable(true);
            categoryBean.setPkgName(bean.getPkgName());
            categoryBean.setDownloadOnGP(bean.isDownloadOnGP());
            if (bean.getChildModules()!=null && bean.getChildModules().size() > 0) {
                // 分类图片取第一个滤镜图片
                categoryBean.setIconUrl(bean.getChildModules().get(0).getIcon());
            }
        }
        return categoryBean;
    }


    @Override
    protected synchronized void notifyDataListener(boolean needUpdate) {
        super.notifyDataListener(needUpdate);
        if (needUpdate && ProcessUtils.isMainProcess(ComponentContext.getContext())) {
            ChildProcessBroadcastReceiver.getInstance().sendBroadcastMsg(ChildProcessBroadcastReceiver.TYPE_REFRESH_STORE_DATA);
        }
    }

    @Override
    public void onMainProcessMsgReceive(int type, int status, Serializable data) {
        if (type == ChildProcessBroadcastReceiver.TYPE_REFRESH_STORE_DATA) {
            loadData();
            notifyDataListener(true);
        }
    }

    @Override
    protected boolean parse(String text) {
        if (TestUser.isTestUser()) {
            // 如果是测试买量用户，尝试读取本地存储卡根目录下json文件，用于测试
            String testFile = Environment.getExternalStorageDirectory() + File.separator + FILE_NAME_STORE;
            String testData = FileUtil.readFileToString(testFile);
            if (!TextUtils.isEmpty(testData)) {
                return super.parse(testData);
            } else {
                return super.parse(text);
            }
        } else {
            return super.parse(text);
        }
    }
}

